package com.yjymm.edu.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yjymm.edu.common.*;
import com.yjymm.edu.model.common.CommonResult;
import com.yjymm.edu.model.common.CommonResultEnum;
import com.yjymm.edu.model.dto.AdminLoginDTO;
import com.yjymm.edu.model.entity.User;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 *  管理员token拦截器
 * @author yjymm
 * @date 2021-01-13 22:47
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    public static String TOKEN_AUTH_NAME;

    private ObjectMapper objectMapper = new ObjectMapper();

    private JwtConfigProperties jwtConfigProperties;

    public TokenInterceptor(JwtConfigProperties jwtConfigProperties) {
        this.jwtConfigProperties = jwtConfigProperties;
        TokenInterceptor.TOKEN_AUTH_NAME = jwtConfigProperties.getAdminTokenName();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (LoginUserContext.getUser() != null) {
            // 验证成功
            return true;
        }
        String token = request.getHeader(TokenInterceptor.TOKEN_AUTH_NAME);
        if (!StringUtils.isEmpty(token)) {
            // 解析token
           try {
               File file = ResourceUtils.getFile(jwtConfigProperties.getPublicKeyPath());
               Payload<User> infoFromToken = JwtUtils.getInfoFromToken(token, RsaUtils.getPublicKeyByFile(file), User.class);
               if (infoFromToken != null) {
                   log.info("token解析成功");
                   log.info("用户信息: {}", infoFromToken);
                   LoginUserContext.setUser(infoFromToken.getUserInfo());
               }
           } catch (Exception e) {
               if (e instanceof ExpiredJwtException){
                   // token过期，提醒用户重新登陆
                   CommonResult build = CommonResult.builder()
                           .code(CommonResultEnum.TOKEN_EXPIRED.getCode())
                           .message(CommonResultEnum.TOKEN_EXPIRED.getMessage())
                           .build();
                   response.getWriter().write(LoginUserContext.getObjectMapper().writeValueAsString(build));
                   return false;
               }
           }
        }

        return true;

    }

}
